package com.cskaoyan.config.smsService;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.ServletContext;
import java.util.Random;

/**
 * @author wxgl
 * @date 2023-01-02 15:49
 * @describe
 */
@NoArgsConstructor
@Data
public class SmsService {

    public static void getMessage(String number, ServletContext context){

        String accessKeyId = "LTAI5t8gpxPTCR6W58RnZq4u";
        String accessKeySecret = "mVPbpbxia0JQotb7HyJAREV8QUuq8h";

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId","cn-hangzhou");
        //手机号
        request.putQueryParameter("PhoneNumbers",number);
        request.putQueryParameter("SignName","stone4j");
        request.putQueryParameter("TemplateCode","SMS_173765187");
        //验证码
        String templateParam = createTemplateParam();
        request.putQueryParameter("TemplateParam",templateParam);

        //将电话号码和验证码放到context域中
        context.setAttribute(number,templateParam);

        try{
            CommonResponse response = client.getCommonResponse(request);
        }catch(Exception e){
            e.printStackTrace();
        }


    }

    public static String createTemplateParam() {
        Random random = new Random();
        String temp = "";
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            temp += num;
        }
        temp = "{\"code\":\"" + temp + "\"}";
        return temp;
    }
}
